// utils/request.js
// 网络请求封装

const app = getApp()

const baseURL = 'http://localhost:10001/api/v1' // 根据实际部署环境修改

/**
 * 网络请求封装
 * @param {Object} options 请求配置
 * @returns {Promise}
 */
function request(options) {
  return new Promise((resolve, reject) => {
    // 添加 token 到请求头
    const header = {
      'Content-Type': 'application/json',
      ...options.header
    }
    
    if (app.globalData.token) {
      header.Authorization = `Bearer ${app.globalData.token}`
    }

    // 构建完整 URL
    const url = options.url.startsWith('http') ? options.url : baseURL + options.url

    wx.request({
      url,
      method: options.method || 'GET',
      data: options.data || {},
      header,
      timeout: options.timeout || 10000,
      success: (res) => {
        console.log('请求成功:', url, res)
        
        // 处理响应
        if (res.statusCode === 200) {
          const data = res.data
          
          // 后端统一响应格式处理
          if (data && data.code !== undefined) {
            if (data.code === 200) {
              resolve(data.data || data)
            } else {
              const errorMsg = data.message || '请求失败'
              wx.showToast({
                title: errorMsg,
                icon: 'none',
                duration: 2000
              })
              reject(new Error(errorMsg))
            }
          } else {
            resolve(data)
          }
        } else if (res.statusCode === 401) {
          // token 过期或无效
          wx.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none',
            duration: 2000
          })
          
          // 清除登录信息
          app.clearLoginInfo()
          
          // 跳转到登录页
          wx.redirectTo({
            url: '/pages/login/login'
          })
          
          reject(new Error('登录已过期'))
        } else {
          const errorMsg = res.data?.message || `请求失败 (${res.statusCode})`
          wx.showToast({
            title: errorMsg,
            icon: 'none',
            duration: 2000
          })
          reject(new Error(errorMsg))
        }
      },
      fail: (err) => {
        console.error('请求失败:', url, err)
        
        let errorMsg = '网络请求失败'
        if (err.errMsg) {
          if (err.errMsg.includes('timeout')) {
            errorMsg = '请求超时，请检查网络'
          } else if (err.errMsg.includes('fail')) {
            errorMsg = '网络连接失败'
          }
        }
        
        wx.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
        
        reject(err)
      }
    })
  })
}

/**
 * GET 请求
 */
function get(url, params = {}, options = {}) {
  return request({
    url,
    method: 'GET',
    data: params,
    ...options
  })
}

/**
 * POST 请求
 */
function post(url, data = {}, options = {}) {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  })
}

/**
 * PUT 请求
 */
function put(url, data = {}, options = {}) {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  })
}

/**
 * DELETE 请求
 */
function del(url, data = {}, options = {}) {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  })
}

/**
 * 文件上传
 */
function upload(url, filePath, formData = {}, options = {}) {
  return new Promise((resolve, reject) => {
    const header = {
      ...options.header
    }
    
    if (app.globalData.token) {
      header.Authorization = `Bearer ${app.globalData.token}`
    }

    wx.uploadFile({
      url: baseURL + url,
      filePath,
      name: 'file',
      formData,
      header,
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          if (data.code === 200) {
            resolve(data.data || data)
          } else {
            reject(new Error(data.message || '上传失败'))
          }
        } catch (e) {
          reject(new Error('响应数据解析失败'))
        }
      },
      fail: reject
    })
  })
}

module.exports = {
  request,
  get,
  post,
  put,
  delete: del,
  upload,
  baseURL
}